Me topé con una pregunta muy interesante y me gustaría saber cómo resolverla mejor en React. Asuma el siguiente código:
const [qrText, setQrText] = useState("") ... const generateQrCode = () => { // set other state inside the "then" QRCode.toDataUrl(qrText).then(...) } const handleChange = (e) => { setQrText(e.target.value) generateQrCode() } Este código no es seguro, ya que las actualizaciones de estado se realizan de forma asincrónica y, cuando se ejecuta generateQrCode , qrText aún podría tener el valor anterior.
Siempre tendí a resolver este problema usando un useEffect con una matriz de dependencia:
const [qrText, setQrText] = useState("") ... const handleChange = (e) => { setQrText(e.target.value) } useEffect(() => { const generateQrCode = () => { // set other state inside the "then" QRCode.toDataUrl(qrText).then(...) } generateQrCode() }, [qrText]) Sin embargo, recientemente vi un video de YouTube de una conferencia de React , donde un ingeniero senior dijo que se supone que useEffect solo se use para sincronizar datos con servicios externos o el DOM. En cambio, las personas deben actualizar el estado solo en los controladores de eventos .
Entonces, ¿es esta la forma correcta de manejar este escenario?
const [qrText, setQrText] = useState("") ... // this now takes the qrText as argument const generateQrCode = (qrTextArg) => { // set other state inside the "then" QRCode.toDataUrl(qrTextArg).then(...) } const handleChange = (e) => { const value = e.target.value setQrText(value) generateQrCode(value) // pass the event value, instead of relying on the "qrText" state }Esto equivaldría al enfoque "basado en eventos", pero se siente un poco imperativo y no "reaccionar".
Así que me pregunto, ¿cuál es la forma prevista de hacer esto?
¡Gracias por tus respuestas!